package com.techstar.mqttprocesser.service.mqtt.config;

import com.alibaba.fastjson.JSON;
import com.techstar.mqttprocesser.service.mqtt.mapper.MqttJsonParseConfigModelMapper;
import com.techstar.mqttprocesser.service.mqtt.model.MqttJsonParseConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lilei
 * @create 2025-03-28-2025/3/28
 */
@Component
@Slf4j
public class DataParseMapConfig {

    @Autowired
    private LogConfig logConfig;

    @Autowired
    private MqttJsonParseConfigModelMapper mqttJsonParseConfigModelMapper;

    /**
     * 这里存储设备名称和topic对应的解析配置
     * key:设备名称-topic
     * value:解析配置
     */
    private static Map<String, List<MqttJsonParseConfig>> dataParseMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {

        List<MqttJsonParseConfig> mqttJsonParseConfigs = mqttJsonParseConfigModelMapper.selectList(null);

        //分组存储解析配置
        mqttJsonParseConfigs.forEach(mqttJsonParseConfig -> {
            String key = mqttJsonParseConfig.getDeviceName() + "-" + mqttJsonParseConfig.getTopic();
            List<MqttJsonParseConfig> mqttJsonParseConfigList = dataParseMap.computeIfAbsent(key, k -> new ArrayList<>());
            //判断是否存在解析配置,如果存在则替换
            mqttJsonParseConfigList.removeIf(config -> config.checkUnique(mqttJsonParseConfig));

            //判断是否存在解析配置,如果不存在则新增
            mqttJsonParseConfigList.add(mqttJsonParseConfig);
        });

        if (logConfig.debugLog()){
            log.info("解析配置加载完成,dataParseMap:{}", JSON.toJSONString(dataParseMap));
        }

    }

    //定时任务，每隔一分钟重新加载一次解析配置
    @Scheduled(cron = "0 0/1 * * * ?")
    public void reload() {
        try {
            init();
        }catch (Exception e){
            log.error("解析配置加载失败", e);
        }
    }


    public static List<MqttJsonParseConfig> getJsonParseConfig(String deviceName, String topic) {
        return dataParseMap.get(deviceName + "-" + topic);
    }

}
